﻿using Newtonsoft.Json;

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Hosting;

namespace MyFileView.Core
{
    public class JsonFileConverter<T>
    {

        public static List<T> Converter(List<T> documentFormats)
            => new JsonFileConverter<T>().ConverterJson(documentFormats);

        public List<T> ConverterJson(List<T> documentFormats)
        {
            StringBuilder stringBuilder = new();
            var path = HostingEnvironment.MapPath("~/");
            using (var fileResult = File.OpenRead(path + "/DocumentFormats.json"))
            using (StreamReader streamReader = new StreamReader(fileResult))
            {
                //   var  res=   JsonConfigurationFileParser.Parse(fileResult);
                if (fileResult.Length < 500000) //50k??
                {
                    stringBuilder.AppendLine(streamReader.ReadToEnd());
                }
                else
                {
                    while (!streamReader.EndOfStream)
                    {
                        stringBuilder.AppendLine(streamReader.ReadLine());
                    }
                    //  var res = JsonConvert.DeserializeObject<DocumentFormatData>(stringBuilder.ToString());
                }
            }
            return ConvertJsonToObject(stringBuilder);
        }
        private List<T> ConvertJsonToObject(StringBuilder stringBuilder)
        {
            try
            {
                return JsonConvert.DeserializeObject<List<T>>(stringBuilder.ToString());
            }
            catch (JsonReaderException ex)
            {
                throw new JsonReaderException("读取documentjson文件转化错误" + ex.Message);
            }
        }
    }



}
